import configAPI from './config.js'
import mpx from '@mpxjs/core'
import apiProxy from '@mpxjs/api-proxy'
import util from '~/utils/util'

mpx.use(apiProxy, {
  usePromise: true
})

const tips = {
  1: '抱歉，出现了一个错误'
}

// 解构
class HTTP {
  request({
    url,
    data = {},
    method = 'GET',
    options = {}
  }) {
    return new Promise((resolve, reject) => {
      options = {
        showLoading: false,
        showError: false,
        ...options
      }
      this._request(url, data, method, options, resolve, reject)
    })
  }

  async _request(url, data, method, options, resolve, reject) {
    const hostUrl = url.match(/^(http|https):/) ? '' : configAPI.HOST_URL
    const cookie = mpx.getStorageSync('userInfoNew').cookie
    const header = {
      'Content-Type': 'application/x-www-form-urlencoded',
      AccessToken: ' LmRlaxA+Ms/BTJMj+vNCVQ1CFshZPgIaEWyzFooW4nDdkhb4nFsHCtRZpjOf41e0zFfT7Zi6',
      Cversion: 'v2.2.3',
      Cookie: cookie
    }
    // 离线终止本次请求
    if (await this._isOffline()) return
    if (options.showLoading) {
      mpx.showToast({
        icon: 'loading',
        title: '加载中...',
        mask: true
      })
    }
    try {
      const reqResult = await mpx.request({
        url: hostUrl + url,
        method,
        data,
        header,
        timeout: configAPI.env === 2 ? 10000 : 20000 // 测试环境有时候接口请求会比较慢, 这里针对环境配置不同超时时间
      }) // 发起网络请求

      if (options.showLoading) mpx.hideToast()
      const code = reqResult.statusCode.toString() // 请求返回的code，用来判定请求是否成功
      if (code.startsWith('2')) {
        console.log(reqResult.data.errno.toString(), 90999999787)
        if (reqResult.data.errno.toString() === '104') {
          mpx.showToast({
            title: reqResult.data.errmsg.toString(),
            icon: 'none'
          })
          wx.redirectTo({ url: '/pages/login/login' })
        } else {
          resolve(reqResult)
        }
      } else {
        reject()
        if (options.showError) {
          mpx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      }
    } catch (err) {
      if (options.showError) {
        mpx.showToast({
          title: res.data.message,
          icon: 'none'
        })
      }
    }
  }

  /**
   * 是否离线
   */
  async _isOffline() {
    const netResult = await mpx.getNetworkType() // 获取网络状态
    const networkType = netResult.networkType.toLowerCase()
    if (networkType === 'none' || networkType === 'notreachable') {
      mpx.showToast({
        title: '网络连接失败',
        icon: 'none',
        mask: true
      })
      return Promise.resolve(true)
    }
    return Promise.resolve(false)
  }
}

export {
  HTTP
}
